from flask import render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from sqlalchemy import func

from . import main
from ..models import Couple, Comment, Vote, Quote, CommentLike
from .. import db
import random
from datetime import datetime
import pytz

@main.route('/')
def index():
    # 获取随机名言
    quote = Quote.query.filter_by(is_active=True).order_by(db.func.random()).first()
    
    # 获取最热门的夫妻
    hot_couple = Couple.query.order_by(Couple.likes_count.desc()).first()
    
    # 获取其他夫妻
    other_couples = Couple.query.order_by(db.func.random()).limit(6).all()
    
    return render_template('index.html',
                         quote=quote,
                         hot_couple=hot_couple,
                         other_couples=other_couples)

@main.route('/couples')
def couples_list():
    page = request.args.get('page', 1, type=int)
    season = request.args.get('season', type=int)  # 获取season参数
    
    # 创建基础查询
    query = Couple.query
    
    # 如果指定了season，添加过滤条件
    if season:
        query = query.filter_by(season=season)
    
    # 应用排序和分页
    couples = query.order_by(Couple.season.desc()).paginate(
        page=page, per_page=12, error_out=False)
    
    max_season = Couple.query.order_by(Couple.season.desc()).first().season
    return render_template('couples_list.html', couples=couples, max_season=max_season)

@main.route('/couple/<int:id>')
def couple_detail(id):
    couple = Couple.query.get_or_404(id)
    # 只获取未隐藏的评论
    comments = couple.comments.filter_by(is_hidden=False).order_by(Comment.timestamp.desc()).all()
    
    # 获取投票信息
    user_vote = None
    if current_user.is_authenticated:
        user_vote = Vote.query.filter_by(user=current_user, couple=couple).first()
    
    # 获取投票统计
    stay_votes = Vote.query.filter_by(couple=couple, vote_type='stay_together').count()
    divorce_votes = Vote.query.filter_by(couple=couple, vote_type='divorce').count()
    
    return render_template('couple_detail.html',
                         couple=couple,
                         comments=comments,
                         user_vote=user_vote,
                         stay_votes=stay_votes,
                         divorce_votes=divorce_votes,
                         current_user=current_user)

@main.route('/comment/<int:couple_id>', methods=['POST'])
@login_required
def add_comment(couple_id):
    data = request.get_json()
    content = data.get('content')
    
    if not content:
        return jsonify({'error': '评论内容不能为空'}), 400
        
    # 使用北京时间
    beijing_tz = pytz.timezone('Asia/Shanghai')
    beijing_time = datetime.now(beijing_tz)
    
    comment = Comment(
        content=content,
        author=current_user,
        couple_id=couple_id,
        timestamp=beijing_time
    )
    db.session.add(comment)
    db.session.commit()
    
    return jsonify({
        'id': comment.id,
        'content': comment.content,
        'author': comment.author.username,
        'timestamp': beijing_time.strftime('%Y-%m-%d %H:%M')
    })

@main.route('/couple/<int:id>/like', methods=['POST'])
@login_required
def like_couple(id):
    couple = Couple.query.get_or_404(id)
    couple.likes_count += 1
    db.session.commit()
    return jsonify({'success': True, 'likes_count': couple.likes_count})

@main.route('/couple/<int:id>/vote', methods=['POST'])
@login_required
def vote_couple(id):
    couple = Couple.query.get_or_404(id)
    vote_type = request.json.get('vote_type')
    
    if vote_type not in ['stay_together', 'divorce']:
        return jsonify({'error': '无效的投票类型'}), 400
    
    # 检查用户是否已经投票
    existing_vote = Vote.query.filter_by(user=current_user, couple=couple).first()
    if existing_vote:
        # 如果投票类型相同，则取消投票
        if existing_vote.vote_type == vote_type:
            db.session.delete(existing_vote)
            db.session.commit()
            stay_votes = Vote.query.filter_by(couple=couple, vote_type='stay_together').count()
            divorce_votes = Vote.query.filter_by(couple=couple, vote_type='divorce').count()
            return jsonify({
                'success': True,
                'vote_cancelled': True,
                'vote_counts': {
                    'stay_together': stay_votes,
                    'divorce': divorce_votes
                }
            })
        # 如果投票类型不同，则更新投票
        else:
            existing_vote.vote_type = vote_type
            db.session.commit()
    else:
        # 创建新投票
        vote = Vote(user=current_user, couple=couple, vote_type=vote_type)
        db.session.add(vote)
        db.session.commit()
    
    # 统计投票结果
    stay_votes = Vote.query.filter_by(couple=couple, vote_type='stay_together').count()
    divorce_votes = Vote.query.filter_by(couple=couple, vote_type='divorce').count()
    
    return jsonify({
        'success': True,
        'vote_counts': {
            'stay_together': stay_votes,
            'divorce': divorce_votes
        }
    })

@main.route('/comment/<int:id>/like', methods=['POST'])
@login_required
def like_comment(id):
    comment = Comment.query.get_or_404(id)
    
    # 检查用户是否已经点赞
    if comment.is_liked_by(current_user):
        return jsonify({'error': '您已经点赞过了'}), 400
        
    like = CommentLike(user_id=current_user.id, comment_id=comment.id)
    comment.likes_count += 1
    db.session.add(like)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'likes_count': comment.likes_count
    })

@main.route('/comment/<int:id>/reply', methods=['POST'])
@login_required
def reply_comment(id):
    parent_comment = Comment.query.get_or_404(id)
    content = request.json.get('content')
    
    if not content:
        return jsonify({'error': '回复内容不能为空'}), 400
    
    # 使用北京时间
    beijing_tz = pytz.timezone('Asia/Shanghai')
    beijing_time = datetime.now(beijing_tz)
        
    reply = Comment(
        content=content,
        author=current_user,
        couple_id=parent_comment.couple_id,
        parent_id=parent_comment.id,
        timestamp=beijing_time
    )
    db.session.add(reply)
    db.session.commit()
    
    return jsonify({
        'id': reply.id,
        'content': reply.content,
        'author': reply.author.username,
        'timestamp': beijing_time.strftime('%Y-%m-%d %H:%M')
    })

@main.route('/search')
def search():
    query = request.args.get('q', '')
    page = request.args.get('page', 1, type=int)
    
    if query:
        couples = Couple.query.filter(
            db.or_(
                Couple.husband_name.contains(query),
                Couple.wife_name.contains(query),
                Couple.story.contains(query)
            )
        ).paginate(page=page, per_page=12, error_out=False)
    else:
        couples = Couple.query.paginate(page=page, per_page=12, error_out=False)
        
    return render_template('search.html', couples=couples, query=query)

@main.route('/comment/<int:id>/unlike', methods=['POST'])
@login_required
def unlike_comment(id):
    comment = Comment.query.get_or_404(id)
    
    # 检查用户是否已经点赞
    like = CommentLike.query.filter_by(user_id=current_user.id, comment_id=comment.id).first()
    if not like:
        return jsonify({'error': '您还没有点赞'}), 400
        
    db.session.delete(like)
    comment.likes_count -= 1
    db.session.commit()
    
    return jsonify({
        'success': True,
        'likes_count': comment.likes_count
    })